package com.ma.service;

import com.ma.NotFoundException;
import com.ma.dao.TagRepository;
import com.ma.po.Tag;

import com.ma.po.Type;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
@Service
public class TagServiceImpl implements TagService{
    @Autowired
    TagRepository tagsRepository;
    @Override
    @Transactional
    public Tag saveTag(Tag tag) {
        return tagsRepository.save(tag);
    }

    @Override
    @Transactional
    public void deleteTag(Long id) {
        tagsRepository.delete(id);
    }

    @Override
    @Transactional
    public Tag updateTag(Long id, Tag tag) {
        Tag t = tagsRepository.findOne(id);
        if( t==null)
            throw new NotFoundException("不存在该标签！");
        BeanUtils.copyProperties(tag,t);
        return tagsRepository.save(t);
    }

    @Override
    @Transactional
    public Tag getTagByName(String name) {
        return tagsRepository.findByName(name);
    }

    @Override
    @Transactional
    public Tag getTag(Long id) {
        return tagsRepository.findOne(id);
    }

    @Override
    @Transactional
    public Page<Tag> ListTag(Pageable pageable) {
        return tagsRepository.findAll(pageable);
    }

    @Override
    public List<Tag> listTags() {
        return tagsRepository.findAll();
    }

    @Override
    public List<Tag> listTagTop(Integer size) {
        Sort sort = new Sort(Sort.Direction.DESC,"blogs.size");
        Pageable pageable = new PageRequest(0, size,sort);

        return tagsRepository.findTop(pageable);
    }

    @Override
    public List<Tag> listTags(String ids) {//1,2,3
        return tagsRepository.findAll(convertToList(ids));
    }



    //将字符串 {1,2,3,...} 转换成数组 [1,2,3,...]
    private  List<Long> convertToList(String ids){

        List<Long> list=new ArrayList<>();
        if(!"".equals(ids) && ids!=null){
            String[] str=ids.split(",");
            for(int i=0;i<str.length;i++)
            {
                list.add(new Long(str[i]));
            }
        }
        return list;

    }


}
